
import java.io.*;
import java.net.*;

public class CalculatePeerStatistics {
	
	public static long calculateDelay(byte[] addr1, int port, int timeoutMs) {
		
		long start = -1; //default check value
		long end = -1; //default check value
		long total = -1; // default for bad connection
		
		//make an unbound socket
		Socket theSock = new Socket();
		
		try {
			InetAddress addr = InetAddress.getByAddress(addr1);
			
			SocketAddress sockaddr = new InetSocketAddress(addr, port);
			
			// Create the socket with a timeout
			//when a timeout occurs, we will get timout exp.
			//also time our connection this gets very close to the real time
			start = System.currentTimeMillis();
			theSock.connect(sockaddr, timeoutMs);
			end = System.currentTimeMillis();
		}
		catch (UnknownHostException e) {
			start = -1;
			end = -1;
		}
		
		catch (SocketTimeoutException e) {
			start = -1;
			end = -1;
		} 
		catch (IOException e) {
			start = -1;
			end = -1;
		} 
		
		finally {
			if (theSock != null) {
				try {
					theSock.close();
				} catch (IOException e) {
				}
			}
			
			if ((start != -1) && (end != -1)) {
				total = end - start;
			}
		}
		
		return total; //returns -1 if timeout
	}
	
	
	public long calculateAvailMem()
	{
		return Runtime.getRuntime().freeMemory();	
	}
	
	public long calculatetotalMem()
	{
		return Runtime.getRuntime().totalMemory();
	}
	
	public static void main(String[] args) {
		
		
        //CalculatePeerStatistics cps = new CalculatePeerStatistics();
		byte[] addr1 = new
		byte[]{(byte)127,(byte)0,(byte)0,(byte)1};
		int port = 4444;
		int timeoutMs = 2000; // 2 seconds
		long value = calculateDelay(addr1, port, timeoutMs);
		System.out.println(value);
		}
	
	
	
}


